package com.wswy.wzcx.ui.message

import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import com.che.libcommon.api.ApiOptionalResultObserver
import com.che.libcommon.api.BaseResult
import com.che.libcommon.api.page.PageList
import com.che.libcommon.api.page.Pagination
import com.che.libcommon.utils.JsonKit
import com.che.libcommon.utils.optional.Optional
import com.wswy.wzcx.api.Api
import com.wswy.wzcx.model.MessageDetail
import com.wswy.wzcx.model.MessageMode
import com.wswy.wzcx.module.base.Resource
import com.wswy.wzcx.module.base.UserViewModel
import com.wswy.wzcx.utils.RxUtils
import io.reactivex.Single

class MessageListViewModel :  UserViewModel() {


    private val listLiveData = MutableLiveData<Resource<List<MessageVO>?>>()

    var pagination: Pagination<MessageVO>? = null
        private set

    fun load(type:String){


        pagination?.release()


        val typeId= MessageMode.getTypeId(type)

        val api: (Int) -> Single<Optional<PageList<MessageVO>>> = {
            Api.get().getMessageList( type,typeId,it).map {

                val data = it.orNull()

                val ret = arrayListOf<MessageVO>()

                data?.list?.forEach {

                    var socialMsg:SocialMsg?=null
                    try {
                        if (typeId == TYPE_SOCIAL){
                            socialMsg = JsonKit.GSON.fromJson(it.extendStr,SocialMsg::class.java)
                        }
                    } catch (e: Exception) {
                    }
                    ret.add(MessageVO(typeId,it,socialMsg))
                }

                Optional.of(PageList.copyPage(ret,data?.pageInfo))

            }.compose(RxUtils.switch2io())
        }

        pagination = if (pagination == null) Pagination<MessageVO>(api) else pagination?.setPaginationWrapper(api)


        pagination?.apply {


            setCallback(object : ApiOptionalResultObserver<List<MessageVO>>() {


                override fun onApiResult(t: List<MessageVO>?) {

                    listLiveData.postValue(Resource.success(t,isFirst))
                }

                override fun onApiError(result: BaseResult<*>?) {
                    if (isFirst){
                        listLiveData.postValue(Resource.error(result,isFirst))
                    }
                }
            })


        }

        pagination?.preLoad()


    }

    fun getMessagesLiveData(): LiveData<Resource<List<MessageVO>?>> = listLiveData

    override fun onCleared() {
        super.onCleared()
        pagination?.release()
    }
}